package com.code2roc.fastface.db;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.code2roc.fastface.util.ScanUtil;
import com.code2roc.fastface.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MapperBeanManage {
    @Autowired
    private ApplicationContext applicationContext;

    private HashMap<String, BaseMapper> mapperDic;

    public MapperBeanManage() {
        mapperDic = new HashMap<>();
    }

    public void initMapperBean(List<Class> runtimeClassList) {
        List<Class> filterClassList = new ArrayList<>();
        filterClassList.add(BaseModel.class);
        List<Class<?>> dataBaseClassList = new ArrayList<>();
        for (Class clazz:runtimeClassList) {
            dataBaseClassList.addAll(ScanUtil.getAllClassByPackageName(clazz.getPackage(), filterClassList));
        }
        Map<String, BaseMapper> res = applicationContext.getBeansOfType(BaseMapper.class);
        for (Class clazz : dataBaseClassList) {
            String tableNameValue = StringUtil.replaceLast(clazz.getSimpleName().toLowerCase(),"do","");
            for (Map.Entry en : res.entrySet()) {
                String mapperTableNameValue =  StringUtil.replaceLast(en.getKey().toString().toLowerCase(),"dao","");
                if (tableNameValue.equals(mapperTableNameValue)) {
                    BaseMapper mapper = (BaseMapper) en.getValue();
                    mapperDic.put(tableNameValue, mapper);
                    break;
                }
            }
        }
        System.out.println("扫描并初始化mapperBean对象成功，mapper数量：" + mapperDic.keySet().size() + "个");
    }

    public BaseMapper getMapper(String tableName) {
        return mapperDic.get(tableName);
    }
}
